package com.xuecheng.base.utils;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * 此类作为视频文件处理父类，提供：
 * 1.查看视频时长
 * 2.校验两个视频的时长是否相等
 * 3.输出流处理waitFor
 */
public class VideoUtil {
    //ffmpeg安装路径
    String ffmpeg_path = "D:\\soft\\ffmpeg\\ffmpeg.exe";

    public VideoUtil(String ffmpeg_path){
        this.ffmpeg_path = ffmpeg_path;
    }

    //获取视频时间(时:分:秒:毫秒)
    public String getVideoTime(String videoPath){
        /*
        * ffmpeg -i lucene.mp4
        * */
        List<String> command = new ArrayList<>();
        command.add(ffmpeg_path);
        command.add("-i");
        command.add(videoPath);
        try{
            ProcessBuilder builder = new ProcessBuilder();
            builder.command(command);
            //将标准输入流和错误输入流合并，通过标准输入流读取信息
            builder.redirectErrorStream(true);
            //执行指令
            Process p = builder.start();
            String outstring = waitFor(p);
            System.out.println(outstring);
            int start = outstring.trim().indexOf("Duration: ");
            if(start > 0){
                int end = outstring.trim().indexOf(", start:");
                if(end > 0){
                    String time = outstring.substring(start + 10,end);
                    if(time != null && !time.equals("")){
                        return time.trim();
                    }
                }
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }

    //检查视频时间是否一致
    public Boolean checkVideoTime(String source,String target){
        String sourceTime = getVideoTime(source);
        sourceTime = sourceTime.substring(0,sourceTime.lastIndexOf("."));
        String targetTime = getVideoTime(target);
        targetTime = targetTime.substring(0,targetTime.lastIndexOf("."));
        if(sourceTime == null || targetTime == null)    return false;
        if(sourceTime.equals(targetTime))   return true;
        return false;
    }

    public String waitFor(Process p){
        InputStream in = null;
        InputStream error = null;
        String result = "error";
        int exitValue = -1;
        StringBuffer outputString = new StringBuffer();
        try{
            in = p.getInputStream();
            error = p.getErrorStream();
            boolean finished = false;
            int maxRetry = 600;     //每次休眠1秒，最长执行10分钟
            int retry = 0;
            while(!finished){
                if(retry > maxRetry){
                    return "error";
                }
                try{
                    while(in.available() > 0){
                        Character c = new Character((char)in.read());
                        outputString.append(c);
                        System.out.println(c);
                    }
                    while(error.available() > 0){
//                        Character c = new Character((char)in.read());
                        Character c = new Character((char)error.read());
                        outputString.append(c);
                        System.out.println(c);
                    }
                    //进程未结束时调用exitValue将抛出异常
                    exitValue = p.exitValue();
                    finished = true;
                }catch(IllegalThreadStateException e){
                    Thread.currentThread().sleep(1000);
                    retry++;
                }
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            if(in != null){
                try{
                    in.close();
                }catch(IOException e){
                    System.out.println(e.getMessage());
                }
            }
        }
        return outputString.toString();
    }
}
